package com.zjl.Zookeeper.第05章_分布式锁;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 速度贼慢
 */
public class B_使用成熟jar {
    private static final Logger log = LoggerFactory.getLogger(B_使用成熟jar.class);

    static int i = 0;
    public static void main(String[] args) {
        InterProcessMutex lock1 =
                new InterProcessMutex(getCuratorFramework(), "/locks");

        log.info("-----------------------------------------------");
        for (int j = 0; j < 100; j++) {
            new Thread(()->{
                try {
                    lock1.acquire();
                    System.out.println("获取到锁" + ++i);
//                    Thread.sleep(100);
                    System.out.println("释放锁" + i);
                    lock1.release();

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }).start();
        }

    }
    private static CuratorFramework getCuratorFramework(){

        ExponentialBackoffRetry exponentialBackoffRetry =
                //重试间隔   毫秒    重试次数  3次
                new ExponentialBackoffRetry(3000, 3);

        CuratorFramework build = CuratorFrameworkFactory
                .builder()
                .connectString("82.157.71.243:2181")//zk地址
                .connectionTimeoutMs(2000)//连接超时时间  毫秒
                .sessionTimeoutMs(2000)//会话超时Ms 毫秒
                .retryPolicy(exponentialBackoffRetry).build();

        build.start();
        System.out.println("------zooKeeper连接成功-----------------");
        return build;
    }
}
